<?php

namespace app\agent\controller;

use app\common\controller\Adminbase;
use app\model\AgentShop;
use app\model\DistributionSetting;
use app\model\AgentAudit;
use app\service\AgentService;

class ShopGoods extends Adminbase
{
    public function index()
    {
        $model = 'AgentAudit';

        $agent = AgentService::getAgentInfo(UID);
        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $query       = AgentShop::field('shop.id, shop.appid, shop.name, g.title, g.product_id, g.commission_rate, g.commission, g.sale_price')
                ->alias('shop')
                ->join('goods g', 'g.shop_appid = shop.appid')
                ->where('shop.agent_id', $agent['id']);
            $count_query = clone $query;

            $list  = $query
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->page($page, $pageSize)
                ->order('g.sort asc, g.id desc')
                ->select();
            $total = $count_query->count();

            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDelBtn(false)
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDataUrl()
            ->setFormUrl('')
            ->setLimit()
            ->setModel($model)
            ->addTableColumn('product_id', '商品ID')
            ->addTableColumn('title', '商品标题', 400)
            ->addTableColumn('name', '小店名称')
            ->addTableColumn('appid', '小店ID')
            ->addTableColumn('sale_price', '销售价格')
            ->addTableColumn('commission_rate', '佣金率（%）')
            ->addTableColumn('commission', '佣金')
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }
}
